<template>
  <div class="rating">
    <div class="stars" :title="`${rating} 分`">
      <span v-for="star in 5" 
            :key="star"
            class="star"
            :class="getStarClass(star)"
            @click="handleClick(star)"
            @mouseover="hoverRating = star"
            @mouseleave="hoverRating = null">
        <i class="fas fa-star"></i>
      </span>
    </div>
    
    <div v-if="showValue" class="rating-value ms-2">
      <span class="fw-bold">{{ displayRating }}</span>
      <span v-if="reviewCount" class="text-muted ms-1">({{ reviewCount }})</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Rating',
  props: {
    rating: {
      type: Number,
      default: 0
    },
    reviewCount: {
      type: Number,
      default: 0
    },
    interactive: {
      type: Boolean,
      default: false
    },
    showValue: {
      type: Boolean,
      default: true
    },
    size: {
      type: String,
      default: 'normal', // 'small', 'normal', 'large'
      validator: (value) => ['small', 'normal', 'large'].includes(value)
    }
  },
  data() {
    return {
      hoverRating: null,
      tempRating: null
    }
  },
  computed: {
    displayRating() {
      return this.tempRating !== null ? this.tempRating : this.rating
    },
    starSize() {
      const sizes = {
        small: '1rem',
        normal: '1.25rem',
        large: '1.5rem'
      }
      return sizes[this.size]
    }
  },
  methods: {
    getStarClass(star) {
      const currentRating = this.hoverRating !== null ? this.hoverRating : this.displayRating
      
      if (star <= currentRating) {
        return 'filled'
      } else if (star - 0.5 <= currentRating) {
        return 'half-filled'
      } else {
        return 'empty'
      }
    },
    handleClick(star) {
      if (this.interactive) {
        this.tempRating = star
        this.$emit('update:rating', star)
        this.$emit('change', star)
      }
    }
  }
}
</script>

<style scoped>
.rating {
  display: inline-flex;
  align-items: center;
}

.stars {
  display: inline-flex;
}

.star {
  color: #ddd;
  cursor: v-bind('interactive ? "pointer" : "default"');
  transition: color 0.2s ease;
  font-size: v-bind(starSize);
}

.star.filled {
  color: #ffc107;
}

.star.half-filled {
  background: linear-gradient(90deg, #ffc107 50%, #ddd 50%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.star:hover {
  transform: v-bind('interactive ? "scale(1.1)" : "scale(1)"');
}

.rating-value {
  font-size: 0.9em;
}
</style>